import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  message,
  Popconfirm,
  Card,
  Row,
  Col,
  Tag,
  Tooltip,
  Badge,
  Descriptions,
  Tabs
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExportOutlined,
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  SettingOutlined,
  BarChartOutlined
} from '@ant-design/icons';
import { ProductApi, ProductVO, ProductPageParams } from '../../../api/iot/product';

const { Option } = Select;
const { TabPane } = Tabs;

const ProductManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState<ProductVO[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchParams, setSearchParams] = useState<ProductPageParams>({});
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<ProductVO | null>(null);
  const [selectedProduct, setSelectedProduct] = useState<ProductVO | null>(null);
  const [form] = Form.useForm();

  // 产品状态选项
  const statusOptions = [
    { label: '开发中', value: 0 },
    { label: '已发布', value: 1 },
    { label: '已停用', value: 2 }
  ];

  // 获取产品列表
  const fetchProducts = async () => {
    setLoading(true);
    try {
      const params = {
        pageNo: current,
        pageSize,
        ...searchParams
      };
      const response = await ProductApi.getProductPage(params);
      setProducts(response.data.list || []);
      setTotal(response.data.total || 0);
    } catch (error) {
      message.error('获取产品列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProducts();
  }, [current, pageSize, searchParams]);

  // 搜索
  const handleSearch = (values: any) => {
    setSearchParams(values);
    setCurrent(1);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({});
    setCurrent(1);
  };

  // 新增产品
  const handleAdd = () => {
    setEditingProduct(null);
    setModalVisible(true);
    form.resetFields();
  };

  // 编辑产品
  const handleEdit = (record: ProductVO) => {
    setEditingProduct(record);
    setModalVisible(true);
    form.setFieldsValue(record);
  };

  // 查看详情
  const handleViewDetail = (record: ProductVO) => {
    setSelectedProduct(record);
    setDetailModalVisible(true);
  };

  // 删除产品
  const handleDelete = async (id: number) => {
    try {
      await ProductApi.deleteProduct(id);
      message.success('删除成功');
      fetchProducts();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 更新产品状态
  const handleUpdateStatus = async (id: number, status: number) => {
    try {
      await ProductApi.updateProductStatus(id, status);
      message.success('状态更新成功');
      fetchProducts();
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  // 保存产品
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      if (editingProduct) {
        await ProductApi.updateProduct({ ...editingProduct, ...values });
        message.success('更新成功');
      } else {
        await ProductApi.createProduct(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchProducts();
    } catch (error) {
      message.error('保存失败');
    }
  };

  // 导出产品
  const handleExport = async () => {
    try {
      await ProductApi.exportProduct(searchParams);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  // 获取状态标签
  const getStatusTag = (status: number) => {
    const statusMap = {
      0: { color: 'orange', text: '开发中' },
      1: { color: 'green', text: '已发布' },
      2: { color: 'red', text: '已停用' }
    };
    const statusInfo = statusMap[status as keyof typeof statusMap] || { color: 'default', text: '未知' };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  // 表格列定义
  const columns = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      ellipsis: true
    },
    {
      title: '产品标识',
      dataIndex: 'productKey',
      key: 'productKey',
      width: 200,
      ellipsis: true
    },
    {
      title: '产品类型',
      dataIndex: 'deviceType',
      key: 'deviceType',
      width: 100,
      render: (type: number) => {
        const typeMap = { 0: '设备', 1: '网关', 2: '子设备' };
        return typeMap[type as keyof typeof typeMap] || '未知';
      }
    },
    {
      title: '设备数量',
      dataIndex: 'deviceCount',
      key: 'deviceCount',
      width: 100,
      render: (count: number) => (
        <Badge count={count} showZero color="#52c41a" />
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: number) => getStatusTag(status)
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: (time: Date) => time ? new Date(time).toLocaleString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right' as const,
      render: (_: any, record: ProductVO) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            >
              详情
            </Button>
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            >
              编辑
            </Button>
          </Tooltip>
          <Tooltip title="配置">
            <Button
              type="link"
              size="small"
              icon={<SettingOutlined />}
              onClick={() => {
                Modal.info({
                  title: '产品配置',
                  content: '产品配置功能开发中...',
                });
              }}
            >
              配置
            </Button>
          </Tooltip>
          <Popconfirm
            title="确定要删除这个产品吗？"
            onConfirm={() => handleDelete(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card>
        <Form
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="name" label="产品名称">
            <Input placeholder="请输入产品名称" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="productKey" label="产品标识">
            <Input placeholder="请输入产品标识" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 120 }} allowClear>
              {statusOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={handleReset} icon={<ReloadOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增产品
            </Button>
            <Button icon={<ExportOutlined />} onClick={handleExport}>
              导出
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={products}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size!);
            }
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新增/编辑模态框 */}
      <Modal
        title={editingProduct ? '编辑产品' : '新增产品'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => setModalVisible(false)}
        width={600}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="产品名称"
                name="name"
                rules={[{ required: true, message: '请输入产品名称' }]}
              >
                <Input placeholder="请输入产品名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="产品标识"
                name="productKey"
                rules={[{ required: true, message: '请输入产品标识' }]}
              >
                <Input placeholder="请输入产品标识" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="产品类型"
                name="deviceType"
                rules={[{ required: true, message: '请选择产品类型' }]}
              >
                <Select placeholder="请选择产品类型">
                  <Option value={0}>设备</Option>
                  <Option value={1}>网关</Option>
                  <Option value={2}>子设备</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="状态"
                name="status"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  {statusOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            label="产品描述"
            name="description"
          >
            <Input.TextArea rows={3} placeholder="请输入产品描述" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 详情模态框 */}
      <Modal
        title="产品详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedProduct && (
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本信息" key="1">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="产品名称">{selectedProduct.name}</Descriptions.Item>
                <Descriptions.Item label="产品标识">{selectedProduct.productKey}</Descriptions.Item>
                <Descriptions.Item label="产品类型">
                  {selectedProduct.deviceType === 0 ? '设备' : selectedProduct.deviceType === 1 ? '网关' : '子设备'}
                </Descriptions.Item>
                <Descriptions.Item label="设备数量">{selectedProduct.deviceCount || 0}</Descriptions.Item>
                <Descriptions.Item label="状态">
                  {getStatusTag(selectedProduct.status!)}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {selectedProduct.createTime ? new Date(selectedProduct.createTime).toLocaleString() : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="产品描述" span={2}>
                  {selectedProduct.description || '-'}
                </Descriptions.Item>
              </Descriptions>
            </TabPane>
            <TabPane tab="设备列表" key="2">
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <BarChartOutlined style={{ fontSize: '48px', color: '#ccc' }} />
                <p style={{ color: '#999', marginTop: '16px' }}>暂无设备数据</p>
              </div>
            </TabPane>
            <TabPane tab="数据统计" key="3">
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <p style={{ color: '#999' }}>暂无统计数据</p>
              </div>
            </TabPane>
          </Tabs>
        )}
      </Modal>
    </div>
  );
};

export default ProductManagement;